package com.weixin1.servlet;

import com.weixin1.bean.Manager;
import com.weixin1.dto.R;
import com.weixin1.service.ManagerService;
import com.weixin1.utils.JSONUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * 登录
 */
@WebServlet("/loginservlet/*")
public class LoginServlet extends HttpServlet {
    ManagerService ms=new ManagerService();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pathInfo = req.getPathInfo().substring(1);

        if("login".equals(pathInfo)){
            login(req,resp);
        }else if("logout".equals(pathInfo)){
            loguot(req,resp);
        }else if("mName".equals(pathInfo)){
            mName(req,resp);
        }else if("update".equals(pathInfo)){
            update(req,resp);
        }
    }

    //修改密码
    private void update(HttpServletRequest req, HttpServletResponse resp) {
        String password1 = req.getParameter("password1");
        String password2 = req.getParameter("password2");
        String name = req.getParameter("name");
        System.out.println(password1);
        System.out.println(password2);
        System.out.println(name);
        try {
            boolean b = ms.update(password2,name,password1);
            System.out.println(b);
            if(b){
                resp.getWriter().print(JSONUtil.toString(R.ok()));
            }else{
                resp.getWriter().print(JSONUtil.toString(R.error()));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //回填用户名
    private void mName(HttpServletRequest req, HttpServletResponse resp) {
        try {
            resp.getWriter().print(JSONUtil.toString(req.getSession().getAttribute("name")));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void loguot(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.getSession().removeAttribute("manager");
        int i=1;
        resp.getWriter().print(JSONUtil.toString(R.ok()));
        System.out.println(i);
    }

    //登录
    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        Manager manager=ms.login(name,password);

        req.getSession().setAttribute("name",name);
        if(manager!=null){
            req.getSession().setAttribute("manager",manager);
            resp.getWriter().write(JSONUtil.toString(R.ok()));
        }else {
            resp.getWriter().write(JSONUtil.toString(R.error()));
        }
    }
}
